package com.quktzhuanka.app.activity;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.base.BaseActivity;
import com.quktzhuanka.app.bean.BuyCarBean;
import com.quktzhuanka.app.bean.GoodsDetailBean;
import com.quktzhuanka.app.bean.Response;
import com.quktzhuanka.app.bean.Selectbean;
import com.quktzhuanka.app.common.SPUtils;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.https.onOKJsonHttpResponseHandler;
import com.quktzhuanka.app.login.WelActivity;
import com.quktzhuanka.app.utils.BannerImageLoader;
import com.quktzhuanka.app.utils.MyScrollView;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class MallGoodsDetailsActivity extends BaseActivity implements MyScrollView.OnScrollListener, IUiListener {

    @BindView(R.id.bg_head2)
    LinearLayout headView;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.homeBanner)
    Banner homeBanner;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.scroll_view)
    MyScrollView scrollView;
    @BindView(R.id.title_tv)
    TextView titleTv;
    @BindView(R.id.txt_merchant_name)
    TextView txtMerchantName;
    @BindView(R.id.txt_price)
    TextView txtPrice;
    @BindView(R.id.txt_old_price)
    TextView txtOldPrice;
    @BindView(R.id.rb_detail)
    TextView rbDetail;
    @BindView(R.id.txt_detail)
    WebView txtDetail;
    private GradientDrawable gradientDrawable;
    private boolean isCollect = false;//未收藏
    private String goods_id = "";
    private TextView tv_num;
    private ImageView iv_img;
    private int goodnum = 1;
    private GoodsDetailBean goodsDetailBean;
    @Override
    protected void initUI() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_mall_goods_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        Drawable drawable1 = getResources().getDrawable(R.mipmap.icon_back_while);
        drawable1.setBounds(0, 0, drawable1.getMinimumWidth(), drawable1.getMinimumHeight());
        tvLeft.setCompoundDrawables(drawable1, null, null, null);
        tvLeft.setVisibility(View.VISIBLE);
        gradientDrawable = (GradientDrawable) tvLeft.getBackground();
        tvTitle.setText("商品详情");
        homeBanner.setImageLoader(new BannerImageLoader());
        homeBanner.setDelayTime(3000);
        goods_id = getIntent().getExtras().getString("goods_id");
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.autoRefresh();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (TextUtils.isEmpty(SPUtils.getStringData(getComeActivity(), Constants.TOKEN, ""))) {
                    openActivity(WelActivity.class);
                    refreshLayout.finishRefresh();
                    return;
                }
                getGoodsMsgRequest();
            }
        });
        headView.getBackground().mutate().setAlpha(0);
        tvTitle.setTextColor(Color.argb(0, 255, 255, 255));
        scrollView.setScrolListener(this);
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY < 100) {
            headView.getBackground().mutate().setAlpha(0);
            tvTitle.setTextColor(Color.argb(0, 255, 255, 255));
            gradientDrawable.setColor(Color.parseColor("#88000000"));
        } else if (scrollY >= 100 && scrollY < 355) {
            if ((scrollY - 100) <= 88) {
                gradientDrawable.setColor(Color.argb((88 - scrollY + 100), 0, 0, 0));
            }
            headView.getBackground().mutate().setAlpha((scrollY - 100));
            tvTitle.setTextColor(Color.argb((scrollY - 100), 255, 255, 255));
        } else {
            tvTitle.setTextColor(Color.argb(255, 255, 255, 255));
            gradientDrawable.setColor(Color.parseColor("#00000000"));
        }
    }

    private void getGoodsMsgRequest() {
        RequestParams requestParams = new RequestParams();
        requestParams.put("goods_id", goods_id);
        HttpUtils.post(Constants.SELF_GOODS_DETAIL, requestParams, new onOKJsonHttpResponseHandler<GoodsDetailBean>(new TypeToken<Response<GoodsDetailBean>>() {
        }) {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(int statusCode, Response<GoodsDetailBean> datas) {
                goodsDetailBean = datas.getData();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishRefresh();
                        List<String> images = new ArrayList<>();
                        if (goodsDetailBean.imglist != null) {
                            for (int i = 0; i < goodsDetailBean.imglist.size(); i++) {
                                images.add(Constants.APP_IP + goodsDetailBean.imglist.get(i).img);
                                homeBanner.update(images);
                            }
                        } else {
                            images.add(Constants.APP_IP + goodsDetailBean.goodsMsg.img);
                            homeBanner.update(images);
                        }
                        homeBanner.start();
                        titleTv.setText(goodsDetailBean.goodsMsg.goods_name);
                        txtMerchantName.setText("销量: "+goodsDetailBean.goodsMsg.sales_volume);
                        txtPrice.setText("￥" + goodsDetailBean.goodsMsg.price);
                        txtOldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        txtOldPrice.setText("原价:￥" + goodsDetailBean.goodsMsg.old_price);
                        txtDetail.loadData(goodsDetailBean.goodsMsg.content == null ? "" :goodsDetailBean.goodsMsg.content.replaceAll("<img", "<img style='width:100%;height:auto'"), "text/html", "utf-8");
                    }
                });
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onComplete(Object o) {

    }

    @Override
    public void onError(UiError uiError) {
    }

    @Override
    public void onCancel() {

    }

    @OnClick({R.id.tv_left,R.id.txt_buy,R.id.img_shop_car,R.id.tv_car})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_shop_car:
                openActivity(MallGoodsCartActivity.class);
                break;
            case R.id.tv_car:
                addToCar();
                break;
            case R.id.tv_left:
                finish();
                break;
            case R.id.txt_buy:
                 List<Selectbean> skuList = new ArrayList<>();
                Bundle bundle = new Bundle();
                    BuyCarBean buyCarBean = new BuyCarBean();
                    buyCarBean.setGoods_id(goodsDetailBean.goodsMsg.goods_id);
                    buyCarBean.setGoods_name(goodsDetailBean.goodsMsg.goods_name);
                    buyCarBean.setImg(goodsDetailBean.goodsMsg.img);
                    buyCarBean.setMerchant_id(goodsDetailBean.goodsMsg.merchant_id);
                    buyCarBean.setNum(goodnum + "");
                    buyCarBean.setOld_price(goodsDetailBean.goodsMsg.old_price);
                    buyCarBean.setPrice(goodsDetailBean.goodsMsg.price);
                    buyCarBean.setPostage(goodsDetailBean.goodsMsg.postage);
                    buyCarBean.setSelectbeans(skuList);
                    List<BuyCarBean> buys = new ArrayList<>();
                    buys.add(buyCarBean);
                    bundle.putSerializable("buyCarBean", (Serializable) buys);
                    openActivity(BuyGoodsActivity.class, bundle);
                break;
        }
    }
    private void addToCar() {
        RequestParams requestParams = new RequestParams();
        JSONArray array = new JSONArray();
        JSONObject object;
        requestParams.put("goods_id", goods_id);
        requestParams.put("goods_num", goodnum);
        Log.d("dsfasd", requestParams.toString());
        HttpUtils.post(Constants.ADD_TO_SHOP_CAR, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    String msg = jsonObject.optString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public class URLImageParser implements Html.ImageGetter {
        TextView mTextView;

        public URLImageParser(TextView textView) {
            this.mTextView = textView;
        }

        @Override
        public Drawable getDrawable(String source) {
            final URLDrawable urlDrawable = new URLDrawable();
            Glide.with(MallGoodsDetailsActivity.this).load(source).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    urlDrawable.bitmap = resource;
                    urlDrawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
                    mTextView.invalidate();
                    mTextView.setText(mTextView.getText());
                }
            });
            return urlDrawable;
        }
    }

    public class URLDrawable extends BitmapDrawable {
        protected Bitmap bitmap;

        @Override
        public void draw(Canvas canvas) {
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());
            }
        }
    }
}
